package com.lifeverse.service;

import com.lifeverse.entity.DigitalDNA;
import com.lifeverse.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * DNA特征映射器
 * 负责将外部特征映射到DNA基因强度，并计算特征哈希
 */
@Slf4j
@Component
public class FeatureMapper {
    
    // 特征到基因的映射权重
    private static final Map<String, Map<String, Double>> FEATURE_TO_GENE_MAPPING = Map.of(
            // 学习相关特征
            "learning_ability", Map.of("learning", 1.0, "logic", 0.6, "adaptability", 0.4),
            "education_level", Map.of("learning", 0.8, "logic", 0.7, "creativity", 0.3),
            "curiosity", Map.of("learning", 0.9, "creativity", 0.7, "adaptability", 0.5),
            
            // 创造力相关特征
            "innovation", Map.of("creativity", 1.0, "intuition", 0.7, "adaptability", 0.5),
            "artistic_ability", Map.of("creativity", 0.9, "emotion", 0.6, "intuition", 0.8),
            "problem_solving", Map.of("creativity", 0.8, "logic", 0.7, "adaptability", 0.6),
            
            // 协作相关特征
            "teamwork", Map.of("collaboration", 1.0, "social", 0.8, "emotion", 0.6),
            "leadership", Map.of("collaboration", 0.8, "social", 0.9, "logic", 0.5),
            "communication", Map.of("collaboration", 0.7, "social", 1.0, "emotion", 0.5),
            
            // 适应性相关特征
            "flexibility", Map.of("adaptability", 1.0, "learning", 0.6, "creativity", 0.5),
            "resilience", Map.of("adaptability", 0.9, "emotion", 0.7, "logic", 0.4),
            "change_tolerance", Map.of("adaptability", 0.8, "emotion", 0.5, "intuition", 0.6),
            
            // 情感相关特征
            "empathy", Map.of("emotion", 1.0, "social", 0.8, "intuition", 0.6),
            "emotional_intelligence", Map.of("emotion", 0.9, "social", 0.7, "adaptability", 0.5),
            "compassion", Map.of("emotion", 0.8, "social", 0.6, "collaboration", 0.7),
            
            // 逻辑相关特征
            "analytical_thinking", Map.of("logic", 1.0, "learning", 0.7, "creativity", 0.3),
            "systematic_approach", Map.of("logic", 0.9, "learning", 0.6, "adaptability", 0.4),
            "critical_thinking", Map.of("logic", 0.8, "learning", 0.8, "creativity", 0.5),
            
            // 直觉相关特征
            "intuitive_thinking", Map.of("intuition", 1.0, "creativity", 0.7, "emotion", 0.6),
            "pattern_recognition", Map.of("intuition", 0.8, "learning", 0.6, "creativity", 0.7),
            "gut_feeling", Map.of("intuition", 0.9, "emotion", 0.8, "adaptability", 0.5),
            
            // 社交相关特征
            "social_skills", Map.of("social", 1.0, "emotion", 0.7, "collaboration", 0.8),
            "networking", Map.of("social", 0.9, "collaboration", 0.6, "adaptability", 0.5),
            "charisma", Map.of("social", 0.8, "emotion", 0.6, "creativity", 0.4)
    );
    
    // 基因强度归一化参数
    private static final BigDecimal MIN_GENE_STRENGTH = BigDecimal.valueOf(10.0);
    private static final BigDecimal MAX_GENE_STRENGTH = BigDecimal.valueOf(90.0);
    private static final BigDecimal DEFAULT_GENE_STRENGTH = BigDecimal.valueOf(50.0);
    
    /**
     * 将特征映射到DNA基因强度
     */
    public void mapFeaturesToDNA(DigitalDNA dna, Map<String, Object> features) {
        log.debug("Mapping features to DNA: {}", dna.getId());
        
        // 初始化基因强度累积器
        Map<String, Double> geneAccumulator = new HashMap<>();
        Map<String, Integer> geneContributorCount = new HashMap<>();
        
        // 初始化所有基因
        initializeGeneAccumulator(geneAccumulator, geneContributorCount);
        
        // 处理每个特征
        for (Map.Entry<String, Object> feature : features.entrySet()) {
            String featureName = feature.getKey();
            Object featureValue = feature.getValue();
            
            // 跳过非数值特征
            if (!(featureValue instanceof Number)) {
                continue;
            }
            
            double value = ((Number) featureValue).doubleValue();
            
            // 获取特征到基因的映射
            Map<String, Double> geneMapping = FEATURE_TO_GENE_MAPPING.get(featureName);
            if (geneMapping != null) {
                // 将特征值分配到相关基因
                for (Map.Entry<String, Double> mapping : geneMapping.entrySet()) {
                    String geneName = mapping.getKey();
                    Double weight = mapping.getValue();
                    
                    double contribution = value * weight;
                    geneAccumulator.put(geneName, geneAccumulator.get(geneName) + contribution);
                    geneContributorCount.put(geneName, geneContributorCount.get(geneName) + 1);
                }
            } else {
                // 处理未知特征：尝试从特征名称推断基因类型
                String inferredGene = inferGeneFromFeatureName(featureName);
                if (inferredGene != null) {
                    geneAccumulator.put(inferredGene, geneAccumulator.get(inferredGene) + value);
                    geneContributorCount.put(inferredGene, geneContributorCount.get(inferredGene) + 1);
                }
            }
        }
        
        // 计算最终基因强度并设置到DNA
        setGeneStrengthsToDNA(dna, geneAccumulator, geneContributorCount);
        
        log.debug("Feature mapping completed for DNA: {}", dna.getId());
    }
    
    /**
     * 计算DNA的特征哈希值
     */
    public String calculateFeatureHash(DigitalDNA dna) {
        try {
            // 构建特征字符串
            StringBuilder featureString = new StringBuilder();
            featureString.append("learning:").append(dna.getLearningGeneStrength()).append(";");
            featureString.append("creativity:").append(dna.getCreativityGeneStrength()).append(";");
            featureString.append("collaboration:").append(dna.getCollaborationGeneStrength()).append(";");
            featureString.append("adaptability:").append(dna.getAdaptabilityGeneStrength()).append(";");
            featureString.append("emotion:").append(dna.getEmotionGeneStrength()).append(";");
            featureString.append("logic:").append(dna.getLogicGeneStrength()).append(";");
            featureString.append("intuition:").append(dna.getIntuitionGeneStrength()).append(";");
            featureString.append("social:").append(dna.getSocialGeneStrength()).append(";");
            featureString.append("generation:").append(dna.getGeneration()).append(";");
            featureString.append("mutation_rate:").append(dna.getMutationRate());
            
            // 计算SHA-256哈希
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(featureString.toString().getBytes());
            
            // 转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            
            return hexString.toString();
            
        } catch (NoSuchAlgorithmException e) {
            log.error("Failed to calculate feature hash for DNA: {}", dna.getId(), e);
            return "hash_error_" + System.currentTimeMillis();
        }
    }
    
    /**
     * 从DNA提取特征向量
     */
    public Map<String, Double> extractFeatureVector(DigitalDNA dna) {
        Map<String, Double> featureVector = new HashMap<>();
        
        // 基础基因特征
        featureVector.put("learning_strength", dna.getLearningGeneStrength().doubleValue());
        featureVector.put("creativity_strength", dna.getCreativityGeneStrength().doubleValue());
        featureVector.put("collaboration_strength", dna.getCollaborationGeneStrength().doubleValue());
        featureVector.put("adaptability_strength", dna.getAdaptabilityGeneStrength().doubleValue());
        featureVector.put("emotion_strength", dna.getEmotionGeneStrength().doubleValue());
        featureVector.put("logic_strength", dna.getLogicGeneStrength().doubleValue());
        featureVector.put("intuition_strength", dna.getIntuitionGeneStrength().doubleValue());
        featureVector.put("social_strength", dna.getSocialGeneStrength().doubleValue());
        
        // 派生特征
        featureVector.put("overall_strength", dna.calculateOverallStrength().doubleValue());
        featureVector.put("fitness_score", dna.getFitnessScore().doubleValue());
        featureVector.put("stability_score", dna.getStabilityScore().doubleValue());
        featureVector.put("expression_activity", dna.getExpressionActivity().doubleValue());
        featureVector.put("mutation_rate", dna.getMutationRate().doubleValue());
        featureVector.put("generation", dna.getGeneration().doubleValue());
        
        // 平衡性特征
        featureVector.put("cognitive_balance", calculateCognitiveBalance(dna));
        featureVector.put("emotional_balance", calculateEmotionalBalance(dna));
        featureVector.put("social_balance", calculateSocialBalance(dna));
        
        // 特化程度特征
        featureVector.put("specialization_degree", calculateSpecializationDegree(dna));
        featureVector.put("versatility_score", calculateVersatilityScore(dna));
        
        return featureVector;
    }
    
    /**
     * 比较两个DNA的特征相似度
     */
    public BigDecimal calculateFeatureSimilarity(DigitalDNA dna1, DigitalDNA dna2) {
        Map<String, Double> features1 = extractFeatureVector(dna1);
        Map<String, Double> features2 = extractFeatureVector(dna2);
        
        double totalSimilarity = 0.0;
        int featureCount = 0;
        
        for (String featureName : features1.keySet()) {
            if (features2.containsKey(featureName)) {
                double value1 = features1.get(featureName);
                double value2 = features2.get(featureName);
                
                // 计算特征相似度（使用余弦相似度的简化版本）
                double similarity = 1.0 - Math.abs(value1 - value2) / Math.max(value1, value2);
                totalSimilarity += Math.max(0, similarity);
                featureCount++;
            }
        }
        
        BigDecimal averageSimilarity = BigDecimal.valueOf(totalSimilarity / featureCount);
        return averageSimilarity.setScale(4, RoundingMode.HALF_UP);
    }
    
    /**
     * 生成DNA的特征摘要
     */
    public Map<String, Object> generateFeatureSummary(DigitalDNA dna) {
        Map<String, Object> summary = new HashMap<>();
        
        // 基本信息
        summary.put("dna_id", dna.getId());
        summary.put("generation", dna.getGeneration());
        summary.put("overall_strength", dna.calculateOverallStrength());
        summary.put("feature_hash", dna.getFeatureHash());
        
        // 主导基因
        summary.put("dominant_genes", identifyDominantGenes(dna));
        summary.put("weak_genes", identifyWeakGenes(dna));
        
        // 特征分类
        summary.put("cognitive_profile", getCognitiveProfile(dna));
        summary.put("emotional_profile", getEmotionalProfile(dna));
        summary.put("social_profile", getSocialProfile(dna));
        
        // 发展潜力
        summary.put("growth_potential", calculateGrowthPotential(dna));
        summary.put("stability_level", getStabilityLevel(dna));
        summary.put("adaptability_level", getAdaptabilityLevel(dna));
        
        return summary;
    }
    
    /**
     * 初始化基因累积器
     */
    private void initializeGeneAccumulator(Map<String, Double> geneAccumulator, Map<String, Integer> geneContributorCount) {
        String[] geneNames = {"learning", "creativity", "collaboration", "adaptability", 
                             "emotion", "logic", "intuition", "social"};
        
        for (String geneName : geneNames) {
            geneAccumulator.put(geneName, 0.0);
            geneContributorCount.put(geneName, 0);
        }
    }
    
    /**
     * 从特征名称推断基因类型
     */
    private String inferGeneFromFeatureName(String featureName) {
        String lowerName = featureName.toLowerCase();
        
        if (lowerName.contains("learn") || lowerName.contains("study") || lowerName.contains("education")) {
            return "learning";
        } else if (lowerName.contains("creat") || lowerName.contains("innovat") || lowerName.contains("art")) {
            return "creativity";
        } else if (lowerName.contains("collaborat") || lowerName.contains("team") || lowerName.contains("cooperat")) {
            return "collaboration";
        } else if (lowerName.contains("adapt") || lowerName.contains("flexib") || lowerName.contains("change")) {
            return "adaptability";
        } else if (lowerName.contains("emotion") || lowerName.contains("feel") || lowerName.contains("empathy")) {
            return "emotion";
        } else if (lowerName.contains("logic") || lowerName.contains("analyt") || lowerName.contains("rational")) {
            return "logic";
        } else if (lowerName.contains("intuit") || lowerName.contains("instinct") || lowerName.contains("gut")) {
            return "intuition";
        } else if (lowerName.contains("social") || lowerName.contains("network") || lowerName.contains("communication")) {
            return "social";
        }
        
        return null; // 无法推断
    }
    
    /**
     * 设置基因强度到DNA
     */
    private void setGeneStrengthsToDNA(DigitalDNA dna, Map<String, Double> geneAccumulator, Map<String, Integer> geneContributorCount) {
        dna.setLearningGeneStrength(calculateFinalGeneStrength("learning", geneAccumulator, geneContributorCount));
        dna.setCreativityGeneStrength(calculateFinalGeneStrength("creativity", geneAccumulator, geneContributorCount));
        dna.setCollaborationGeneStrength(calculateFinalGeneStrength("collaboration", geneAccumulator, geneContributorCount));
        dna.setAdaptabilityGeneStrength(calculateFinalGeneStrength("adaptability", geneAccumulator, geneContributorCount));
        dna.setEmotionGeneStrength(calculateFinalGeneStrength("emotion", geneAccumulator, geneContributorCount));
        dna.setLogicGeneStrength(calculateFinalGeneStrength("logic", geneAccumulator, geneContributorCount));
        dna.setIntuitionGeneStrength(calculateFinalGeneStrength("intuition", geneAccumulator, geneContributorCount));
        dna.setSocialGeneStrength(calculateFinalGeneStrength("social", geneAccumulator, geneContributorCount));
    }
    
    /**
     * 计算最终基因强度
     */
    private BigDecimal calculateFinalGeneStrength(String geneName, Map<String, Double> geneAccumulator, Map<String, Integer> geneContributorCount) {
        double accumulated = geneAccumulator.get(geneName);
        int contributorCount = geneContributorCount.get(geneName);
        
        BigDecimal finalStrength;
        if (contributorCount > 0) {
            // 计算平均值
            double average = accumulated / contributorCount;
            finalStrength = BigDecimal.valueOf(average);
        } else {
            // 使用默认值
            finalStrength = DEFAULT_GENE_STRENGTH;
        }
        
        // 归一化到有效范围
        finalStrength = finalStrength.max(MIN_GENE_STRENGTH).min(MAX_GENE_STRENGTH);
        
        return finalStrength.setScale(2, RoundingMode.HALF_UP);
    }
    
    /**
     * 计算认知平衡度
     */
    private double calculateCognitiveBalance(DigitalDNA dna) {
        double learning = dna.getLearningGeneStrength().doubleValue();
        double creativity = dna.getCreativityGeneStrength().doubleValue();
        double logic = dna.getLogicGeneStrength().doubleValue();
        double intuition = dna.getIntuitionGeneStrength().doubleValue();
        
        double mean = (learning + creativity + logic + intuition) / 4.0;
        double variance = (Math.pow(learning - mean, 2) + Math.pow(creativity - mean, 2) + 
                          Math.pow(logic - mean, 2) + Math.pow(intuition - mean, 2)) / 4.0;
        
        return Math.max(0, 1.0 - Math.sqrt(variance) / 50.0); // 归一化到0-1
    }
    
    /**
     * 计算情感平衡度
     */
    private double calculateEmotionalBalance(DigitalDNA dna) {
        double emotion = dna.getEmotionGeneStrength().doubleValue();
        double logic = dna.getLogicGeneStrength().doubleValue();
        
        // 情感和逻辑的平衡
        double difference = Math.abs(emotion - logic);
        return Math.max(0, 1.0 - difference / 100.0);
    }
    
    /**
     * 计算社交平衡度
     */
    private double calculateSocialBalance(DigitalDNA dna) {
        double social = dna.getSocialGeneStrength().doubleValue();
        double collaboration = dna.getCollaborationGeneStrength().doubleValue();
        double emotion = dna.getEmotionGeneStrength().doubleValue();
        
        double mean = (social + collaboration + emotion) / 3.0;
        double variance = (Math.pow(social - mean, 2) + Math.pow(collaboration - mean, 2) + 
                          Math.pow(emotion - mean, 2)) / 3.0;
        
        return Math.max(0, 1.0 - Math.sqrt(variance) / 50.0);
    }
    
    /**
     * 计算特化程度
     */
    private double calculateSpecializationDegree(DigitalDNA dna) {
        double[] strengths = {
                dna.getLearningGeneStrength().doubleValue(),
                dna.getCreativityGeneStrength().doubleValue(),
                dna.getCollaborationGeneStrength().doubleValue(),
                dna.getAdaptabilityGeneStrength().doubleValue(),
                dna.getEmotionGeneStrength().doubleValue(),
                dna.getLogicGeneStrength().doubleValue(),
                dna.getIntuitionGeneStrength().doubleValue(),
                dna.getSocialGeneStrength().doubleValue()
        };
        
        double max = 0;
        double sum = 0;
        for (double strength : strengths) {
            max = Math.max(max, strength);
            sum += strength;
        }
        
        return max / (sum / strengths.length); // 最大值与平均值的比率
    }
    
    /**
     * 计算多样性分数
     */
    private double calculateVersatilityScore(DigitalDNA dna) {
        return 2.0 - calculateSpecializationDegree(dna); // 与特化程度相反
    }
    
    /**
     * 识别主导基因
     */
    private String[] identifyDominantGenes(DigitalDNA dna) {
        Map<String, Double> geneStrengths = Map.of(
                "learning", dna.getLearningGeneStrength().doubleValue(),
                "creativity", dna.getCreativityGeneStrength().doubleValue(),
                "collaboration", dna.getCollaborationGeneStrength().doubleValue(),
                "adaptability", dna.getAdaptabilityGeneStrength().doubleValue(),
                "emotion", dna.getEmotionGeneStrength().doubleValue(),
                "logic", dna.getLogicGeneStrength().doubleValue(),
                "intuition", dna.getIntuitionGeneStrength().doubleValue(),
                "social", dna.getSocialGeneStrength().doubleValue()
        );
        
        return geneStrengths.entrySet().stream()
                .filter(entry -> entry.getValue() > 70.0)
                .map(Map.Entry::getKey)
                .toArray(String[]::new);
    }
    
    /**
     * 识别弱势基因
     */
    private String[] identifyWeakGenes(DigitalDNA dna) {
        Map<String, Double> geneStrengths = Map.of(
                "learning", dna.getLearningGeneStrength().doubleValue(),
                "creativity", dna.getCreativityGeneStrength().doubleValue(),
                "collaboration", dna.getCollaborationGeneStrength().doubleValue(),
                "adaptability", dna.getAdaptabilityGeneStrength().doubleValue(),
                "emotion", dna.getEmotionGeneStrength().doubleValue(),
                "logic", dna.getLogicGeneStrength().doubleValue(),
                "intuition", dna.getIntuitionGeneStrength().doubleValue(),
                "social", dna.getSocialGeneStrength().doubleValue()
        );
        
        return geneStrengths.entrySet().stream()
                .filter(entry -> entry.getValue() < 30.0)
                .map(Map.Entry::getKey)
                .toArray(String[]::new);
    }
    
    /**
     * 获取认知档案
     */
    private String getCognitiveProfile(DigitalDNA dna) {
        double learning = dna.getLearningGeneStrength().doubleValue();
        double logic = dna.getLogicGeneStrength().doubleValue();
        double creativity = dna.getCreativityGeneStrength().doubleValue();
        
        if (learning > 70 && logic > 70) return "analytical_learner";
        if (creativity > 70 && learning > 60) return "creative_learner";
        if (logic > 70 && creativity < 40) return "systematic_thinker";
        if (creativity > 70 && logic < 40) return "creative_thinker";
        return "balanced_cognitive";
    }
    
    /**
     * 获取情感档案
     */
    private String getEmotionalProfile(DigitalDNA dna) {
        double emotion = dna.getEmotionGeneStrength().doubleValue();
        double intuition = dna.getIntuitionGeneStrength().doubleValue();
        double logic = dna.getLogicGeneStrength().doubleValue();
        
        if (emotion > 70 && intuition > 60) return "emotionally_intuitive";
        if (emotion > 70 && logic > 60) return "emotionally_rational";
        if (emotion < 40 && logic > 70) return "highly_rational";
        if (emotion > 70) return "emotionally_driven";
        return "emotionally_balanced";
    }
    
    /**
     * 获取社交档案
     */
    private String getSocialProfile(DigitalDNA dna) {
        double social = dna.getSocialGeneStrength().doubleValue();
        double collaboration = dna.getCollaborationGeneStrength().doubleValue();
        double emotion = dna.getEmotionGeneStrength().doubleValue();
        
        if (social > 70 && collaboration > 70) return "highly_social";
        if (collaboration > 70 && emotion > 60) return "empathetic_collaborator";
        if (social > 70 && emotion < 50) return "strategic_networker";
        if (social < 40 && collaboration < 40) return "independent_worker";
        return "socially_balanced";
    }
    
    /**
     * 计算成长潜力
     */
    private double calculateGrowthPotential(DigitalDNA dna) {
        double adaptability = dna.getAdaptabilityGeneStrength().doubleValue();
        double learning = dna.getLearningGeneStrength().doubleValue();
        double stability = dna.getStabilityScore().doubleValue();
        
        // 成长潜力 = (适应性 + 学习能力) / 2 * (1 - 稳定性/200)
        // 稳定性太高可能限制成长
        return (adaptability + learning) / 2.0 * (1.0 - stability / 200.0);
    }
    
    /**
     * 获取稳定性等级
     */
    private String getStabilityLevel(DigitalDNA dna) {
        double stability = dna.getStabilityScore().doubleValue();
        
        if (stability > 90) return "highly_stable";
        if (stability > 70) return "stable";
        if (stability > 50) return "moderately_stable";
        if (stability > 30) return "unstable";
        return "highly_unstable";
    }
    
    /**
     * 获取适应性等级
     */
    private String getAdaptabilityLevel(DigitalDNA dna) {
        double adaptability = dna.getAdaptabilityGeneStrength().doubleValue();
        
        if (adaptability > 80) return "highly_adaptable";
        if (adaptability > 60) return "adaptable";
        if (adaptability > 40) return "moderately_adaptable";
        if (adaptability > 20) return "low_adaptability";
        return "rigid";
    }
}